#include "../lib/session.hpp"
#include <unistd.h>
#include <boost/algorithm/string.hpp>

#include <iostream>

using namespace std;

Session::Session(int sockfd)
{
    sockfd_ = sockfd;
    CmdHeader header;
    if(::read(sockfd_, &header, sizeof(header)) < 0)
    {
        ok_ = false;
        return;
    }
    if(header.cmd != HEADER_HANDSHAKE_COMMAND)
    {
        ok_ = false;
        return;
    }
    ok_ = true;
    char buff[header.payloadLen +1];
    ::read(sockfd_, buff, header.payloadLen);
    buff[header.payloadLen] = '\0';
    name_ = buff;
}

Session::~Session()
{
    ::close(sockfd_);
}

int Session::getSock()
{
    return sockfd_;
}

bool Session::isOk()
{
    return ok_;
}

std::string Session::getName()
{
    return name_;
}

bool Session::write(CmdHeader header, std::vector <std::string> args)
{
    std::string data = "";
    for(uint i = 0; i < args.size() - 1; i++)
    {
        data += args[i];
        data += PIPC_PROTOCOL_DELIMITER;
    }
    if(args.size() > 0)
        data += args[args.size() -1];
    header.payloadLen = data.length();
    if(::write(sockfd_, &header, sizeof(header)) < 0)
    {
        ok_ = false;
        return false;
    }
    ::write(sockfd_, data.c_str(), data.length());
    return true;
}

CmdHeader Session::readHeader()
{
    CmdHeader header;
    bzero(&header, sizeof(header));
    if(::read(sockfd_, &header, sizeof(header)) < 0)
        ok_=false;
    return header;
}

std::vector <std::string> Session::readArgs(int size)
{
    std::vector <std::string> ret;
    char buff[size+1];
    if(::read(sockfd_, &buff, size) < 0)
    {
        ok_ = false;
        return ret;
    }
    buff[size] = '\0';
    std::string stringBuff = buff;
    boost::split(ret,stringBuff,boost::is_any_of(PIPC_PROTOCOL_DELIMITER));
    return ret;
}

